package com.example.ivideo_2211a.home

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.common.mvi.NetworkResult
import com.example.common.mvi.SingleEvent
import kotlinx.coroutines.launch

/**
 * Home页面的ViewModel
 */
class HomeViewModel : BaseViewModel<HomeIntent, HomeViewState, HomeResult>() {
    
    private val repository = HomeRepository()
    
    override fun initialState(): HomeViewState = HomeViewState()
    
    override suspend fun handleIntent(intent: HomeIntent) {
        when (intent) {
            is HomeIntent.LoadVideos -> loadVideos()
            is HomeIntent.RefreshVideos -> refreshVideos()
            is HomeIntent.LoadMoreVideos -> loadMoreVideos(intent.page)
        }
    }
    
    /**
     * 加载视频列表
     */
    private fun loadVideos() {
        viewModelScope.launch {
            repository.getRecommendVideos(1).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        updateState(currentState().copy(isLoading = true, error = null))//显示加载中
                    }
                    is NetworkResult.Success<List<HomeData>> -> {
                        updateState(
                            currentState().copy(
                                isLoading = false,
                                videos = result.data,
                                currentPage = 1,
                                hasMore = result.data.size >= 10
                            )
                        )
                    }
                    is NetworkResult.Error -> {
                        updateState(
                            currentState().copy(
                                isLoading = false,
                                error = result.exception.message ?: "加载失败"
                            )
                        )
                        sendEvent(SingleEvent.ShowError(result.exception.message ?: "加载失败"))
                    }
                }
            }
        }
    }
    
    /**
     * 刷新视频列表
     */
    private fun refreshVideos() {
        viewModelScope.launch {
            repository.getRecommendVideos(1).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        updateState(currentState().copy(isRefreshing = true, error = null))
                    }
                    is NetworkResult.Success<List<HomeData>> -> {
                        updateState(
                            currentState().copy(
                                isRefreshing = false,
                                videos = result.data,
                                currentPage = 1,
                                hasMore = result.data.size >= 10
                            )
                        )
                        sendEvent(SingleEvent.ShowToast("刷新成功"))
                    }
                    is NetworkResult.Error -> {
                        updateState(
                            currentState().copy(
                                isRefreshing = false,
                                error = result.exception.message ?: "刷新失败"
                            )
                        )
                        sendEvent(SingleEvent.ShowError(result.exception.message ?: "刷新失败"))
                    }
                }
            }
        }
    }
    
    /**
     * 加载更多视频
     */
    private fun loadMoreVideos(page: Int) {
        if (currentState().isLoadingMore || !currentState().hasMore) return
        
        viewModelScope.launch {
            repository.getRecommendVideos(page).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        updateState(currentState().copy(isLoadingMore = true))
                    }
                    is NetworkResult.Success<List<HomeData>> -> {
                        val newVideos = currentState().videos + result.data
                        updateState(
                            currentState().copy(
                                isLoadingMore = false,
                                videos = newVideos,
                                currentPage = page,
                                hasMore = result.data.size >= 10
                            )
                        )
                    }
                    is NetworkResult.Error -> {
                        updateState(currentState().copy(isLoadingMore = false))
                        sendEvent(SingleEvent.ShowError(result.exception.message ?: "加载更多失败"))
                    }
                }
            }
        }
    }
}